package com.wxw.getapp.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.safframework.log.L;
import com.wxw.getapp.R;
import com.wxw.getapp.bean.AppInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

/**
 * Created by Administrator on 2018/11/14.
 */

public class GetApk {

    private static PackageManager mPackageManager;
    private static String BACKUP_PATH = Environment.getExternalStorageDirectory().toString() + "/提取APP/";
    private static final String APK = ".apk";
    private static final String ODEX = ".odex";
    private static final String OAT32 = "oat/arm";
    private static final String OAT64 = "oat/arm64";
    private static Context cotentc;
    private static ProgressDialog dialog;

    public GetApk(Context context) {
        this.cotentc = context;


    }

    public static void setBackupPath(String backupPath) {
        BACKUP_PATH = backupPath;
    }

    private static Drawable getAppIcon(PackageInfo packageInfo) {
        return packageInfo.applicationInfo.loadIcon(mPackageManager);
    }

    private static String getAppName(PackageInfo packageInfo) {
        return packageInfo.applicationInfo.loadLabel(mPackageManager)
                .toString();
    }

    private static String getAppPackageName(PackageInfo packageInfo) {
        return packageInfo.packageName;
    }

    private static String getAppSourceDir(PackageInfo packageInfo) {
        return packageInfo.applicationInfo.sourceDir;
    }

    private static int maxsize ;
    private static int diff ;
    private static final int EVENT_COMPLETE = 1;
    private static final int EVENT_MOVE = 2;
    private static final int EVENT_INIT = 0;
    private static Handler mH = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_COMPLETE:
                    dialog.dismiss();
                    Toast.makeText(cotentc,"<<<提取完成>>>",Toast.LENGTH_SHORT).show();
                    break;
                    case EVENT_MOVE:
                        dialog.incrementProgressBy(diff);
                    break;
                    case EVENT_INIT:
                        initDownloadDailog(maxsize);
                    break;
            }
        }
    };

    public static void backupApp(AppInfo appInfo, Context context) {
        cotentc = context;

        mPackageManager = context.getPackageManager();
        PackageInfo packageInfo = appInfo.getInfo();
        String source = getAppSourceDir(packageInfo);
        if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
            String key = getAppName(packageInfo);
            String dest = BACKUP_PATH + key + APK;
//            Toast.makeText(cotentc, R.string.app_name, Toast.LENGTH_SHORT)
//                    .show();
            new Thread(new CopyRunnable(source, dest, key)).start();
        } else {
            String path = new File(source).getParent();
            String name = new File(source).getName();
            name = name.substring(0, name.indexOf(APK));

            String kitKat = new File(path).getParent() + File.separator + name
                    + ODEX;
            String oat32 = path + File.separator + OAT32 + File.separator
                    + name + ODEX;
            String oat64 = path + File.separator + OAT64 + File.separator
                    + name + ODEX;

            if (!new File(kitKat).exists() && !new File(oat32).exists()
                    && !new File(oat64).exists()) {
                String key = getAppName(packageInfo);
                if (getAppIcon(packageInfo).equals(
                        getAppPackageName(packageInfo))) {
                    key = name;
                }
                String dest = BACKUP_PATH + key + APK;
//                Toast.makeText(cotentc, R.string.app_name, Toast.LENGTH_SHORT)
//                        .show();
                new Thread(new CopyRunnable(source, dest, key)).start();
            } else {
//                Toast.makeText(cotentc, R.string.app_name, Toast.LENGTH_SHORT)
//                        .show();
            }
        }
    }

    private static class CopyRunnable implements Runnable {

        private String source;
        private String dest;
        private String key;

        public CopyRunnable(String source, String dest, String key) {
            this.source = source;
            this.dest = dest;
            this.key = key;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub

            try {
                int length = 1024 * 1024;

                if (!new File(BACKUP_PATH).exists()) {
                    new File(BACKUP_PATH).mkdirs();
                }

                File fDest = new File(dest);
                if (fDest.exists()) {
                    fDest.delete();
                }
                fDest.createNewFile();
                FileInputStream in = new FileInputStream(new File(source));
                FileOutputStream out = new FileOutputStream(fDest);
                FileChannel inC = in.getChannel();
                FileChannel outC = out.getChannel();
                //TODO 初始化进度
                maxsize = (int) inC.size();
                mH.sendEmptyMessage(EVENT_INIT);

                int low_position = 0;
                while (true) {
                    if (inC.position() == inC.size()) {
                        inC.close();
                        outC.close();
                        //TODO 结束进度
                        mH.sendEmptyMessage(EVENT_COMPLETE);
//                        Message message = mH.obtainMessage(EVENT_COMPLETE);
////                        message.obj = cotentc.getString(R.string.app_name, key, dest);
//                        mH.sendEmptyMessage(1);
                        break;
                    }
                    Thread.sleep(25);
                    //TODO 更新进度
                    diff = (int) (inC.position() - low_position);
                    mH.sendEmptyMessage(EVENT_MOVE);

                    low_position = (int) inC.position();
                    if ((inC.size() - inC.position()) < 1024 * 1024) {
                        length = (int) (inC.size() - inC.position());
                    } else {
                        length = 1024 * 1024;
                    }
                    inC.transferTo(inC.position(), length, outC);
                    inC.position(inC.position() + length);

//                    i++;
                }
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("zhouyj", e.toString());
            }

        }
    }

    private static void initDownloadDailog(int max) {
        // 进度条还有二级进度条的那种形式，这里就不演示了
        dialog = new ProgressDialog(cotentc);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        dialog.setCancelable(false);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setIcon(R.mipmap.logo);// 设置提示的title的图标，默认是没有的
        dialog.setProgressNumberFormat(" ");//右下角数字进度
        dialog.setTitle("提取中");
        dialog.setMax(max);
//        dialog.setMessage("这是一个水平进度条");
//        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
//                new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
//        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
//                new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });


        L.e("eee","显示弹窗");
        dialog.show();
//        new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//                int i = 0;
//                while (i < 100) {
//                    try {
//                        Thread.sleep(200);
//                        // 更新进度条的进度,可以在子线程中更新进度条进度
//                        dialog.incrementProgressBy(1);
//                        // dialog.incrementSecondaryProgressBy(10)//二级进度条更新方式
//                        i++;
//
//                    } catch (Exception e) {
//
//                    }
//                }
//                // 在进度条走完时删除Dialog
//                dialog.dismiss();
//
//            }
//        }).start();
    }
}
